﻿package GFlash
{
	import flash.net.Socket;
	import flash.events.*;
	import flash.utils.*;

	public class GSocket extends Socket
	{

		private var gIP:String = "";
		private var gPort:int = -1;

		private var gConnectTimer:uint = 0;
		private var gIsConnected:Boolean = false;
		private var gCallBackFun:Function; 
		
		public function GSocket(IP:String, Port:int)
		{
			trace("Warnning:Socket must be build for exe or air!!!!!");
			if(IP.length==0)
			{
				trace("Error:Invalid IP Address!!!");
				return;
			}
			if(Port<=0)
			{
				trace("Error:Invalid Port!!!");
				return;
			}
			gIP = IP;
			gPort = Port;
			
			this.addEventListener(Event.CONNECT,onConnect);
			this.addEventListener(Event.CLOSE,onClose);
			this.addEventListener(IOErrorEvent.IO_ERROR,onIOError);
            this.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
			
			gConnectTimer=setInterval(onConnectTimerTick,1000);
     
		}
		
		private function onConnectTimerTick():void
		{
			if(!gIsConnected)
			{
				this.connect(gIP, gPort);
				trace("正在连接服务器[IP:"+gIP+"]");
			}else
			{
				clearInterval(gConnectTimer);
			}
		}
		private function onConnect(e:Event):void
		{
			gIsConnected = true;
			//this.endian = Endian.BIG_ENDIAN;
			trace("已经成功连接服务器");
			clearInterval(gConnectTimer);
		}

		private function onClose(e:Event):void
		{
			//断网重连
			gIsConnected = false;
			gConnectTimer=setInterval(onConnectTimerTick,1000);
		}
        private function onSocketData(e:ProgressEvent):void
		{
			if(gIsConnected)
			{
				var len:uint= this.bytesAvailable;    
				var charSet:String=this.readUTFBytes(len);
				gCallBackFun(charSet);
			}
		}
		private function onIOError(e:IOErrorEvent):void
		{
			trace(e.text);
		}
		public function SetCallBackFun(fun:Function)
		{
			gCallBackFun=fun;
		}
		public function SendSocket(msg:String):void
		{
			this.writeUTFBytes(msg);
			this.flush();
		}
	// ... Class End ...
	}
	
}
